<?php
include_once (S_ROOT . './source/function_user.php');
include_once (S_ROOT . './source/api_class.php');

class Data {
    public $id;
    public $uid;
    public $type;
    public $token;
    public $access;
    public $tpls;
    public $list_name;
    public $apis;
    public $scope;
    public $start  = 0;
    public $length = 50;
    
    public function __construct($uid, $type, $token, $access, $id) {
        $this->id    = $id;
        $this->uid   = $uid;
        $this->type  = $type;
        $this->token = $token;
        $this->access= $access;
        $this->tpls       = array('card'=>'会员卡片','desk'=>'书桌店','emotion' => '表情', 'paper' => '信纸', 'font' => '字体', 'skin' => '皮肤', 'proemotion' => '表情VIP', 'propaper' => '信纸VIP');
        $this->list_name  = array('emotions', 'papers', 'fonts', 'skins','desks','cards');
        $this->apis       = array(
                                'list'      =>  array('getCardList','getDeskList','getEmotionList', 'getPaperList', 'getFontList', 'getSkinList', 'getProEmotionList', 'getProPaperList'),
                                'detail'    =>  array('getCardDetail','getDeskDetail','getEmotionDetail', 'getPaperDetail', 'getFontDetail', 'getSkinDetail'),
                                'add'       =>  array('addCard','addDesk','addEmotion', 'addPaper', 'addFont', 'addSkin'),
                                'edit'      =>  array('editCard','editDesk','editEmotion', 'editPaper', 'editFont', 'editSkin'),
        						'batch'		=>  array('setBatchData'),
        						'zip'	=>  array('getShopzipList','getShopZipInfo','editShopZipInfo','addShopZip'),
                                'countlist' =>  array('getCardCountList','getPaperCountList','getEmotionCountList','getFontCountList','getSkinCountList','getDeskCountList'),
        );
        $this->scope = array(
            'addEmotion' => array('min'=>20001,'max'=>29999),
            'addPaper'   => array('min'=>10001,'max'=>19999),
            'addFont'    => array('min'=>30001,'max'=>39999),
            'addSkin'    => array('min'=>40001,'max'=>49999),
			'addDesk'	 => array('min'=>130001,'max'=>139999),
			'addCard'	 => array('min'=>140001,'max'=>149999),
        );
    }
    
    public function execute ($action) {
        $do = $this->getDo ($action);
      
        return $this->$do($action);
    }
    
    public function editShopZipInfo($action){
    	$result = $this->zipRequest($action);
    	if($result){
    		echo 1;
    		exit;
    	}
    	echo 0;
    	exit;
    	 
    }
    
    public function addShopZip($action){
    	$result = $this->zipRequest($action);
    	if($result){
    		echo 1;
    		exit;
    	}
    	echo 0;
    	exit;
    	
    }
    
    private function zipRequest($action){
    	 $param=array(
    	 		'do'			=> 'shop',
    	 		'action'		=> $action,
    	 		'format'        =>  'json',
			 	'type'			=> intval($_GET['type']) ? intval($_GET['type']) : 5,
    	 		'pid'			=> intval($_GET['pid']),
    	 		'status'		=> intval($_GET['status']),
    	 		'platform'		=> strval($_GET['platform']),
    	 		'min_version'	=> strval($_GET['min_version']),
    	 		'max_version'	=> strval($_GET['max_version']),
    	 		'zip_size'		=> intval($_GET['zip_size']),
    	 		'zip_url'		=> strval($_GET['zip_url']),
    	 );
    	 if($action == 'editShopZipInfo'){
    	 	$param['id'] = intval($_GET['id']);
    	 }
    	 return $this->requestApi($action, $param);
    }
    
    public function getShopZipInfo($action){
   
    	$result= $this->shopDetailRequest($action);
    	$detail= $this->resultZipDetail($result);
    	$data['detail'] = $detail;
    	header("Content-type: application/json");
    	echo json_encode($data);
    	exit;
      
    }
    
    private function resultZipDetail($result){
    	$status_css		=	array('0'=>'','1'=>'');
    	$platform_css	=   array('pinkdiaryandroid'=>'','pinkdiaryios'=>'','pinkdiaryproios'=>'');
    	$status_css[$result['status']]		= 'selected';
    	$platform_css[$result['platform']]	= 'selected';
    	$result['status_css']	=	$status_css;
    	$result['platform_css']	=	$platform_css;
		
		return $result; 
    }
    
    public function getShopzipList($action){  
    	$result = $this->shopListRequest($action);
    	$data['list']    = $result;
    	$data['pageUrl'] = $this->paging($action,$_GET['platform']);
    	return render('shop_zip_list', $data);
    }
    
    private function paging($action,$platform=''){
        if($platform){
            $action.='&platform='.$platform;
        }
    	$mpurl  = 'admin.php?ac=shop_class&op='.$action;
    	$start  = empty($_GET['start'])?$this->start:$_GET['start'];
    	$length = empty($_GET['length'])?$this->length:$_GET['length'];
    	 
    	$pageUrl=multi($start, $length, $mpurl);
    	return $pageUrl;
    }
    
    /**
     * 批量操作
     * @param unknown $action
     */
    public function setBatchData($action){
    
    	// 组装请求服务器的数据
    	$param = array(
    			'do'        =>  'shop',
    			'format'    =>  'json',
    			'action'    =>  $action,
    			'uid'       =>  $this->uid,
  				'actionType'=>  strval($_GET['actionType']),
    			'ids'		=>  json_encode($_GET['ids']),
    			'editType'	=>  strval($_GET['editType'])
    	);
    	$result =  $this->requestApi($action, $param);
    	 if($result){
    	 	echo 1;
    	 	exit;
    	 }
    	 echo 0;
        exit;
    }
    
    /**
     * 获取商品列表
     * @param unknown $action
     * @return string
     */
    public function getShopList ($action) { 
        // 请求表情列表数据
        $result   = $this->shopListRequest($action);      
        $list     = $this->resultListData($result);   
        // 通用变量
        $data = $this->styleVariable($action);
        $data['list'] = $list;
     
    	$data['pageUrl']=$this->paging($action);

        return render('shop_list', $data);
    }

    /**
     * 获取商品下载量列表
     * @param unknown $action
     * @return string
     */
    public function getPaperCountLists ($action) {
        $req  = request();
        $name = $req['name'];
        // 请求表情列表数据
        $list = $this->paperCountListRequest($action);
        $info = $this->styleVariable($action);
        $data = array(
            'list' => array_reverse($list),
            'info' => $info,
            'name' => $name
        );
        return render('paper_count_list', $data);
    }
    
    /**
     * 获取商品详情
     * @param unknown $action
     * @return string
     */
    public function getShopDetail ($action) {
        // 请求表情详情数据
        $result   = $this->shopDetailRequest($action);
       	
        $detail   = $this->goodsDetailData($result);
      
        // 通用变量
        $datas = $this->styleVariable($action);
        $datas['detail'] = $detail;
        header("Content-type: application/json");
       	echo json_encode($datas);
       	exit;
    }
    
    // 编辑商品
    public function editShop ($action) {
    	
        // 请求表情详情数据
        $result   = $this->shopEditRequest($action);
     
        if ($result) {
        	echo 1;
        	exit;
        }
        echo 0;
        exit;
    }

    // 统计手账资源下载量
    private function paperCountListRequest ($action) {
        // 组装请求服务器的数据
        $param = array(
            'do'        =>  'shop',
            'format'    =>  'json',
            'action'    =>  $action,
            'type'      =>  $this->type,
            'id'        =>  $this->id,
        );
        $result = $this->requestApi($action, $param);
        return $result;
    }

    public function addShop ($action) {
    	header("Content-type: application/json");
        // 请求表情详情数据
        $result   = $this->shopAddRequest($action);
       
        if ($result) {
        	echo 1;
        	exit;
        }
        echo 0;
        exit;
    }
    
    // 请求服务器商店列表数据
    private function shopListRequest ($action) {
        // 组装请求服务器的数据
        $param = array(
        	'do'        =>  'shop',
        	'format'    =>  'json',
            'action'    =>  $action,
            'uid'       =>  $this->uid,
            'type'      =>  $this->type,
            'id'        =>  $this->id,
            'start'     =>  empty($_GET['start'])?$this->start:$_GET['start'],
            'length'    =>  empty($_GET['length'])?$this->length:$_GET['length']
        );
        isset($_GET['pid']) 	 && $param['pid'] 		= $_GET['pid'];
        isset($_GET['platform']) && $param['platform'] 	= $_GET['platform'];
        isset($_GET['n_type'])     && $param['n_type']  = $_GET['n_type'];
        $result =  $this->requestApi($action, $param);
     
        return $result;
    }
    
    // 请求服务器商品详情数据
    private function shopDetailRequest ($action) {
        $param = array(
            'do'        =>  'shop',
        	'format'    =>  'json',
            'action'    =>  $action,
            'uid'       =>  $this->uid,
            'id'        =>  $this->id
        );
        
        return $this->requestApi($action, $param);
    }
    
    // 请求服务器编辑商品
    private function shopEditRequest ($action) {
        $param = $this->goodsEditOrAddData($action);
        
        return $this->requestApi($action, $param);
    }
    
    // 请求服务器添加商品
    private function shopAddRequest ($action) {
        $param = $this->goodsEditOrAddData($action);
   
        return $this->requestApi($action, $param);
    }

    private function verifyId($action){
        $id = intval($_GET['id']);
        $res = false;
        if($this->scope[$action] && $id >= $this->scope[$action]['min'] && $id <=$this->scope[$action]['max']){
            $res = true;
        }
        return $res;
    }

    private function goodsEditOrAddData ($action) {
    
        $info = array(
        	'do'        =>  'shop',
        	'format'    =>  'json',
            'id'              =>    intval($_GET['id']),
            'name'            =>    urlencode(strval($_GET['name'])),
            'expire_time'     =>    intval($_GET['expire_time']),
            'status'          =>    intval($_GET['status']),
            'label'           =>    intval($_GET['label']),
            'vip'             =>    intval($_GET['vip']),
            'name_tag'        =>    intval($_GET['name_tag']),
            'tag'             =>    strval($_GET['tag']),
            'zip_size'        =>    intval($_GET['zip_size']),
            'zip_url'         =>    strval($_GET['download_url']),
            'sale_amount'     =>    intval($_GET['sale_amount']),
            'price_orign'     =>    intval($_GET['price_orign']),
            'price_final'     =>    intval($_GET['price_final']),
            'cuid'            =>    intval($_GET['cuid']) ? intval($_GET['cuid']) : '3',
            'desc'            =>    urlencode(strval($_GET['desc'])),
            'cover'           =>    strval($_GET['cover']) ? strval($_GET['cover']) :'static/img/default_sz.jpg',
            'cover_s'         =>    strval($_GET['cover']),
            'background'      =>    strval($_GET['background']),
            'thumbnail'       =>    $this->thumbailImportData($action, $_GET['thumbnail_m'], $_GET['thumbnail_s']),
            'task'            =>    $this->taskImportData(),
            'action'          =>    $action
        );
     
        return $info;
    }
    
    // 商品详情数据
    private function goodsDetailData ($result) {
        if (empty($result)) return array();
        
        // 通用显示
        $key_arr = array('id', 'name', 'desc', 'cover', 'background', 'expire_time', 'vip',
            'dateline','zip_size', 'sale_amount','price_orign', 'price_final', 'download_url'
        );
        $data = $this->assembleReplacedFieldData($result, $key_arr);
        
        // 状态显示
        $status     = $result['status'];
        $status_css = $this->cssShowSelected($status);

        // 资源样式显示
        $name_tag     = $result['name_tag']['bg'];
        $name_tag_css = $this->cssShowSelected($name_tag);
        
        // vip样式显示
        $vip     = $result['vip'];
        $vip_css = $this->cssShowSelected($vip);
        
        // 标签显示
        $tag     = $result['tag'][0]['bg'];
        $tag_css = array();
        if (!empty($tag)) {
            $tag_css = $this->cssShowSelected($tag);
        }
      
        // 任务
        $task = '';
        if (!empty($result['task'])) {
           $task_type = $result['task']['type'];
           $task_num  = $result['task']['num'];
           $task_msg = $result['task']['desc'];
           $taskdesc = $task_type.'|'.$task_num.'|'.$task_msg;
        }
        
        // 预览图显示(根据不同)
        $thumbnail = $this->thumbailExportData($result['download_url'], $result['thumbnail']);
        
        // 商品作者
        $author_uid = $result['author']['uid'];
        
        $data['status_css']     = $status_css;
        $data['name_tag_css']   = $name_tag_css;
        $data['vip_css']   = $vip_css;
        $data['tag_css']   = $tag_css;
        $data['taskdesc']	   = $taskdesc;
//         $data['task_type'] = $task_type;
//         $data['task_num']  = $task_num;
//         $data['task_msg'] = $task_msg;
        $data['thumbnail'] = $thumbnail;
        $data['cuid']      = $author_uid;
        
        return $data;
    }
    
    // 组装预览图的显示数据
    private function thumbailExportData ($download_url, $thumbnail) {
        $goods_info = $this->parseDownLoadUrl($download_url);

        $thumbnail_s = $thumbnail_m = array();
        switch ($goods_info['type']) {
            case 'paper':
                $baseUrl = "http://d.fenfenriji.com/diary/paper/".$goods_info['id']."/priview/";
                $url = array();
                $thumbnails = explode(',', $thumbnail);
                foreach($thumbnails as $value){
                    $url[] = mb_substr($value,strlen($baseUrl));
                }
                $thumbnail_s = $thumbnail_m = implode(',',$url);
                break;
            case 'emotion':
                $baseUrl_s = "http://d.fenfenriji.com/diary/emotion/".$goods_info['id']."/priview/".$goods_info['name']."_";
                $baseUrl_m = "http://d.fenfenriji.com/diary/emotion/".$goods_info['id']."/".$goods_info['name']."/".$goods_info['name']."_";
            
                // 处理预览图
                foreach ($thumbnail as $value){
                    $m_arr[]   = mb_substr($value['m'],strlen($baseUrl_m));
                    $s_arr[] = mb_substr($value['s'],strlen($baseUrl_s));
                }
                $thumbnail_m = implode(',', $m_arr);
                $thumbnail_s = implode(',', $s_arr);
                break;
            case 'font':
                $baseUrl = "http://d.fenfenriji.com/diary/font/".$goods_info['id']."/priview/";
                $url = array();
                $thumbnails = explode(',', $thumbnail);
                foreach($thumbnails as $value){
                    $url[] = mb_substr($value,strlen($baseUrl));
                }
                $thumbnail_s = $thumbnail_m = implode(',',$url);
                break;
            case 'appskin':
                $baseUrl = "http://d.fenfenriji.com/diary/appskin/android/".$goods_info['id']."/priview/";
                $url = array();
                $thumbnails = explode(',', $thumbnail);
                
                foreach($thumbnails as $value){
                    $url[] = mb_substr($value,strlen($baseUrl));
                }
                $thumbnail_s = $thumbnail_m = implode(',',$url);
                break;
        }
        
        return array('m' => $thumbnail_m, 's' => $thumbnail_s);
    }
    
    // 组装预览图的修改数据
    private function thumbailImportData ($action, $thumbnail_m, $thumbnail_s = '') {
        $thumbs = array();
        switch ($action) {
            case in_array($action, array('editPaper', 'addPaper', 'editSkin', 'addSkin', 'editFont', 'addFont')):
                if (!empty($thumbnail_m)) {
                    $thumbs = explode(',', trim($thumbnail_m));
                }
                break;
            case in_array($action, array('editEmotion', 'addEmotion')):
                if (!empty($thumbnail_m) && !empty($thumbnail_s)){
                    // 处理预览图
                    $thumbs_m = explode(',', trim($thumbnail_m));
                    $thumbs_s = explode(',', trim($thumbnail_s));
                    for ($i = 0;$i < count($thumbs_m) ; $i ++){
                        $tmp = array(
                                's'    =>    $thumbs_s[$i],
                                'm'    =>    $thumbs_m[$i]
                        );
                        $thumbs[] = $tmp;
                    }
                }
                break;
        }
        
        if (empty($thumbs)) return '';
        
        return json_encode($thumbs);
    }
    
    private function taskImportData () {
       $taskArr = array();
        $task=$_GET['task'];
        !empty($_GET['task_type']) && $task=$_GET['task_type']."|".$_GET['task_num'].'|'.$_GET['task_msg'];
        if (!empty($task)) {
            $taskarray = explode('|', $task);
            $taskArr = array(
                'type'    =>    $taskarray[0],
                'num'     =>    $taskarray[1],
                'desc'    =>    $taskarray[2]
            );
        }
     
        if (empty($taskArr)) return '';
      
       return JsonFormat($taskArr);
    }
    
    // 解析下载包链接的地址
    private function parseDownLoadUrl ($download_url) {
        $parts = parse_url($download_url);
        $path  = trim($parts['path'], '/');
        $path_arr = explode('/', $path);
        if (empty($path_arr)) return array();
        
        $goods_type = $path_arr[1];
        $goods_id   = $path_arr[2];
        $goods_name = substr($path_arr[3], 0, strpos($path_arr[3], '_'));
        if ($goods_type == 'appskin') {
            $goods_id   = $path_arr[3];
            $goods_name = substr($path_arr[4], 0, strpos($path_arr[4], '_'));
        }
        
        return array('type' => $goods_type, 'id' => $goods_id, 'name' => $goods_name);
    }
    
    // 样式显示相关变量返回
    private function styleVariable ($action) {
        // 通用变量,样式的显示
        $common = $this->apiAndTplName($action);
    
        $result = array(
            'active'        => array($common['goods'] => " class=\"active\""),         // 侧边栏被选择的样式
            'goods'         => ucfirst($common['goods']),   // 商品名
            'goods_name'    => $common['goods_name'],        // 商品名(中文显示)
            'access'        => $this->access
        );
    
        return $result;
    }
    
    // 样式被选定显示
    private function cssShowActive ($attribute) {
        return array($attribute => " class = \" active\"");
    }
    
    // 样式被选定显示
    private function cssShowSelected ($attribute) {
        return array($attribute => " selected");
    }
    
    
    // 处理返回的数据，返回模板渲染用的数据
    private function resultListData ($result) {
        if (empty($result)) return array();
    
        // 处理返回数据
        foreach ($this->list_name as $tpl) {
            if (!empty($result[$tpl])) {
                return $result[$tpl];
            }
        }
    
        return array();
    }
    
    // 组装返回模板及其他需要的变量
    private function apiAndTplName ($action) {
        if (empty($action)) return array();
    
        // 转小写
        $action = strtolower($action);

        // 返回模板名
        foreach ($this->tpls as $good => $name) {
            if (strpos($action, $good)) {               
                  return array('goods' => $good, 'goods_name' => $this->tpls [$good]);             
            }
        }
    
        return array();
    }

    // 返回通用字段
    private function assembleReplacedFieldData ($import, $key_arr = array()) {
        if (empty($key_arr)) {
            return $import;
        }
    
        $result = array();
        foreach ($key_arr as $val) {
            if (isset($import[$val])) {
                $result[$val] = strval($import[$val]);
            }
        }
    
        return $result;
    }
    
    // 获取请求方法
    private function getDo ($action) {
        $do = '';
        switch ($action) {
            case in_array($action, $this->apis['list']) :
                $do = 'getShopList';
                break;
            case in_array($action, $this->apis['detail']) :
                $do = 'getShopDetail';
                break;
            case in_array($action, $this->apis['add']) :
                $do = 'addShop';
                break;
            case in_array($action, $this->apis['edit']) :
                $do = 'editShop';
                break;
            case in_array($action, $this->apis['batch']) :
                $do = 'setBatchData';
                break;  
            case in_array($action, $this->apis['zip']) :
                $do = $action;
                break;
            case in_array($action, $this->apis['countlist']) :
                $do = 'getPaperCountLists';
                break;
        }
                            
        return $do;  
    }
    
    // 请求api
    private function requestApi ($action, $param) {
         // 实例化
        global $_SC;
        $param['action'] = $action;

        $result=get_api_content($_SC['apiurl'], $param);
      
        $result=json_decode($result,TRUE);
    
        $result=$result['resultData'];
        // 请求管理接口返回数据
        return $result;
    }
    
    // 模板渲染
    private function render ($tpl, $data) {
        // 从数组中把变量导入到当前的符号表中
        extract($data, EXTR_SKIP);
        
        // 使用全局变量
        global $_SGLOBAL;
        
        // 开始输出缓冲, 这时PHP停止输出, 在这以后的输出都被转到一个内部的缓冲里.
        ob_start();
        
        try {
            // 加载本地模板
            include template($tpl);
        } catch (Exception $e) {
            // 删除输出缓冲区
            ob_end_clean();
        
            // 抛出异常
            throw $e;
        }
        
        // 结束输出缓冲, 并扔掉缓冲里的内容.
        return ob_get_clean();
    }
}

// 管理员
$id       = 0;
$type     = 'new';
$uid      = $_SGLOBAL ['supe_uid'];
$token    = $_SGLOBAL['token'];
$action   = 'getPaperList';
$access   = in_array($uid,$_SGLOBAL['adminuids']);
if ($_GET['id'])   $id     = intval($_GET['id']);
if ($_GET['op'])   $action = strval($_GET['op']);
if ($_GET['type']) $type = strval($_GET['type']);
$data['list'] = $list;

// 初始化
$data = new Data($uid, $type, $token, $access, $id);
echo $data->execute($action);
exit();